from hashlib import md5
import json
import argparse
import os
import shutil
import time

parser = argparse.ArgumentParser()
parser.add_argument('--file', help='files to read and write')
args = parser.parse_args()

if not args.file:
    print('资源文件路径混淆失败')
    exit(1)

handle_files = ['.png', '.webp', '.jpg', '.jpeg']
md5_salt = "sups"  # 替换salt ssh-keygen -t ed25519 -C "ying.junjie@olaola.chat"
try:
    with open(args.file, "r") as srcFile:
        items = json.load(srcFile)
        asset_dir = os.path.dirname(args.file)
        print(f"混淆资源文件路径: {asset_dir}")
        for key in items:
            file_name, file_extension = os.path.splitext(key)  # 拆分一下名称和扩展名
            if not file_extension in handle_files:  # 如果不在忽略名单里，
                continue
            if key.startswith("packages"):
                new_values = []
                for value in items[key]:
                    filename = os.path.splitext(value)[0].split("/")[-1]
                    origin = f"{filename}_{md5_salt}"
                    md5_value = md5(origin.encode('utf-8')).hexdigest()
                    new_file_name = value.replace(
                        filename+file_extension, md5_value+file_extension)

                    print(new_file_name)
                    if os.path.exists(os.path.join(asset_dir, value)):
                        shutil.move(os.path.join(asset_dir, value),
                                    os.path.join(asset_dir, new_file_name))
                        new_values.append(new_file_name)
                        writefile = "micu"
                        file = os.path.join(asset_dir, new_file_name)
                        if file.endswith('.png') or file.endswith('.jpg') or file.endswith('.jpeg')  or file.endswith('.webp'):
                            with open(file, "a") as f:
                                f.write(str(writefile))
                items[key] = new_values

        with open(args.file, "w") as destfile:
            json.dump(items, destfile, ensure_ascii=False)
except Exception as e:
    print('资源文件路径混淆失败333333333: ' + e)
    exit(1)
